// pages/forum-detail/forum-detail.js
const app = getApp();
const util = require('../../utils/util.js');

Page({
  data: {
    postId: null,
    post: {
      images: []
    },
    commentList: [],
    commentContent: '',
    isLiked: false,
    isAuthor: false
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ postId: options.id });
      this.loadPostDetail(options.id);
      this.loadComments(options.id);
      this.checkIfLiked(options.id);
    }
  },

  loadPostDetail(id) {
    app.showLoading();
    const userInfo = wx.getStorageSync('userInfo');
    const userId = userInfo ? userInfo.id : null;

    app.request({
      url: `/forum/posts/${id}`,
      method: 'GET',
      data: userId ? { userId: userId } : {}
    }).then(res => {
      if ((res.code === 200 || res.success) && res.data) {
        const images = res.data.images ? (typeof res.data.images === 'string' ? res.data.images.split(',') : []) : [];
        this.setData({
          post: {
            ...res.data,
            images: images,
            createTime: util.formatDateTime(res.data.createTime)
          },
          isAuthor: userInfo && userInfo.id === res.data.userId
        });
      }
    }).catch(err => {
      app.showToast('加载失败');
      console.error(err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  loadComments(postId) {
    app.request({
      url: `/forum/posts/${postId}/comments`,
      method: 'GET'
    }).then(res => {
      if (res.code === 200 || res.success) {
        const comments = ((res.data && res.data.list) || res.data || []).map(comment => ({
          ...comment,
          createTime: util.formatDateTime(comment.createTime)
        }));
        this.setData({
          commentList: comments
        });
      }
    }).catch(err => {
      console.error('加载评论失败', err);
    });
  },

  // 检查是否已点赞
  checkIfLiked(postId) {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) return;

    app.request({
      url: `/forum/posts/${postId}/like`,
      method: 'GET',
      data: { userId: userInfo.id }
    }).then(res => {
      if (res.code === 200) {
        this.setData({
          isLiked: res.data
        });
      }
    }).catch(err => {
      console.error('检查点赞状态失败', err);
    });
  },

  // 点赞/取消点赞
  toggleLike() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      app.showToast('请先登录');
      wx.navigateTo({
        url: '/pages/login/login'
      });
      return;
    }

    app.request({
      url: `/forum/posts/${this.data.postId}/like?userId=${userInfo.id}`,
      method: 'POST'
    }).then(res => {
      if (res.code === 200) {
        const isLiked = res.data;
        this.setData({
          isLiked: isLiked
        });
        app.showToast(isLiked ? '点赞成功' : '取消点赞', 'success');
        // 重新加载帖子详情以更新点赞数
        this.loadPostDetail(this.data.postId);
      } else {
        app.showToast(res.message || '操作失败');
      }
    }).catch(err => {
      app.showToast('操作失败，请稍后重试');
      console.error('点赞操作失败', err);
    });
  },

  // 评论输入
  onCommentInput(e) {
    this.setData({
      commentContent: e.detail.value
    });
  },

  // 发表评论
  submitComment() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      app.showToast('请先登录');
      wx.navigateTo({
        url: '/pages/login/login'
      });
      return;
    }

    if (!this.data.commentContent.trim()) {
      app.showToast('请输入评论内容');
      return;
    }

    app.showLoading();
    app.request({
      url: `/forum/posts/${this.data.postId}/comments?userId=${userInfo.id}`,
      method: 'POST',
      data: {
        content: this.data.commentContent
      }
    }).then(res => {
      if (res.code === 200) {
        app.showToast('评论成功', 'success');
        this.setData({
          commentContent: ''
        });
        // 重新加载评论列表和帖子详情
        this.loadComments(this.data.postId);
        this.loadPostDetail(this.data.postId);
      } else {
        app.showToast(res.message || '评论失败');
      }
    }).catch(err => {
      app.showToast('评论失败，请稍后重试');
      console.error('发表评论失败', err);
    }).finally(() => {
      app.hideLoading();
    });
  },

  // 删除帖子
  deletePost() {
    wx.showModal({
      title: '提示',
      content: '确定要删除这篇帖子吗？删除后无法恢复',
      success: (res) => {
        if (res.confirm) {
          const userInfo = wx.getStorageSync('userInfo');
          app.showLoading();
          app.request({
            url: `/forum/posts/${this.data.postId}?userId=${userInfo.id}`,
            method: 'DELETE'
          }).then(res => {
            if (res.code === 200) {
              app.showToast('删除成功', 'success');
              setTimeout(() => {
                wx.navigateBack();
              }, 1000);
            } else {
              app.showToast(res.message || '删除失败');
            }
          }).catch(err => {
            app.showToast('删除失败，请稍后重试');
            console.error('删除帖子失败', err);
          }).finally(() => {
            app.hideLoading();
          });
        }
      }
    });
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: this.data.post.images
    });
  }
});


